<template>
  <el-dialog
    :title="isEdit ? '编辑部门' : '添加子部门'"
    :visible="dialogVisible"
    :before-close="handleClose"
  >
    <el-form ref="form" :model="form" label-width="120px" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="form.name"
          style="width: 80%"
          placeholder="1-50个字符"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="form.code"
          style="width: 80%"
          placeholder="1-50个字符"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item label="部门管理者" prop="manager">
        <el-select
          v-model="form.manager"
          :loading="selectLoading"
          loading-text="加载中..."
          placeholder="请选择"
          @focus="getEmployessList"
        >
          <el-option
            v-for="item in employeesList"
            :key="item.id"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="form.introduce"
          type="textarea"
          style="width: 80%"
          placeholder="1-300个字符"
          :rows="3"
          maxlength="300"
        />
      </el-form-item>
    </el-form>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="handleClose">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="addDept"
        >确 定</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getDepartments, addDepartment, updateDepartment, getDepartmentDtail } from '@/api/departments'
import { getEmployessList } from '@/api/employess'
export default {
  name: 'AddDept',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    node: {
      type: Object,
      default: () => {}
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    const checkNameRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      let repeat = null
      if (this.isEdit) {
        // 修改 判断同级 obj.pid === this.node.pid
        repeat = depts
          .filter(obj => obj.pid === this.node.pid && obj.id !== this.node.id)
          .some(obj => obj.name === value)
      } else {
        // 添加子级 判断子级 obj.pid === this.node.id
        repeat = depts
          .filter(obj => obj.pid === this.node.id)
          .some(obj => obj.name === value)
      }
      repeat
        ? callback(new Error('已有此部门，请确认后重新添加'))
        : callback()
    }
    const checkCodeRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      let repeat = null
      if (this.isEdit) {
        repeat = depts
          .filter(obj => obj.id !== this.node.id)
          .some(obj => obj.code === value && value) // 如果value为空字符串时，允许重复，所以 && value
      } else {
        repeat = depts
          .some(obj => obj.code === value && value)// 如果value为空字符串时，允许重复，所以 && value
      }
      repeat
        ? callback(new Error('已有编码，请更改后重新添加'))
        : callback()
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      rules: {
        name: [
          { trigger: 'blur', required: true, message: '部门名称不能为空' },
          { trigger: 'blur', validator: checkNameRepeat }
        ],
        code: [
          { trigger: 'blur', required: true, message: '部门编码不能为空' },
          { trigger: 'blur', validator: checkCodeRepeat }
        ],
        manager: [
          { trigger: 'blur', required: true, message: '部门管理者为必选项' }
        ],
        introduce: [
          { trigger: 'blur', required: true, message: '部门介绍不能为空' }
        ]
      },
      employeesList: [],
      selectLoading: true // select是否正在加载数据
    }
  },
  async created() {
    if (this.isEdit) {
      this.form = await getDepartmentDtail(this.node.id)
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:dialogVisible', false)
      this.$refs.form.resetFields()
    },
    async getEmployessList() {
      this.employeesList = await getEmployessList()
      this.selectLoading = false
    },
    addDept() {
      // try {
      this.$refs.form.validate(async isok => {
        if (isok) {
          if (this.isEdit) {
            await updateDepartment(this.form)
            this.$message.success('修改成功')
          } else {
            await addDepartment({ ...this.form, pid: this.node.id })
            this.$message.success('添加成功')
          }
          this.handleClose()
          this.$emit('addDepartment')
        }
      })
      // } catch (err) {
      //   this.$message.error(err)
      // }
    }
  }
}
</script>

<style>
</style>
